<template>
  <div>
    <h1>商品管理</h1>
  </div>
  <!-- 多条件查询 -->
  <div>
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="关键字">
        <el-input v-model="searchForm.keyWord" placeholder="关键字" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onQuetty">查询</el-button>
      </el-form-item>
    </el-form>
  </div>
  <el-button type="primary" @click="ShowAddProd">添加商品</el-button>
  <!-- 表格 -->
  <div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="prodId" label="ID" width="50" />
      <el-table-column prop="prodName" label="商品名称" width="150" />
      <el-table-column prop="prodPrice" label="商品价格" width="60" />
      <el-table-column prop="statusName" label="商品状态" width="60" />
      <el-table-column prop="nickName" label="商家" width="60" />
      <el-table-column prop="typeName" label="商品类型" width="80" />
      <el-table-column label="商品图片" width="200">
        <template #default="scope">
          <el-image
            style="width: 50px; height: 50px; border-radius: 20%"
            v-if="
              scope.row.prodImageList != null &&
              scope.row.prodImageList.length > 0
            "
            fit="cover"
            v-for="item in scope.row.prodImageList"
            :key="item.imageId"
            :src="item.imageUrl"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200" />
      <el-table-column prop="reason" label="驳回原因" width="150" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            size="small"
            v-if="scope.row.prodStatus == 1"
            type="primary"
            @click="checkProd(scope.row)"
            >审核</el-button
          >
          <el-button
            size="small"
            v-if="scope.row.prodStatus == 0"
            type="success"
            @click="UpLine(scope.row)"
            >上线</el-button
          >
          <el-button
            size="small"
            v-if="scope.row.prodStatus == 2"
            type="info"
            @click="DownLine(scope.row)"
            >下线</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 分页 -->
  <div style="margin-top: 20px">
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="searchForm.pageNum"
        v-model:page-size="searchForm.pageSize"
        :page-sizes="[2, 3, 4, 5]"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <!-- 添加对话框q -->
  <div>
    <el-dialog v-model="dialogFormVisible" title="添加对话框" width="500">
      <el-form :model="form">
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="form.prodName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品价格" :label-width="formLabelWidth">
          <el-input v-model="form.prodPrice" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品类型" :label-width="formLabelWidth">
          <el-select
            v-model="form.prodType"
            placeholder="请选择商品类型"
            size="large"
            style="width: 240px"
            clearable
          >
            <el-option
              v-for="item in typeList"
              :key="item.dictId"
              :label="item.dictLable"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片" :label-width="formLabelWidth">
          <el-upload
            v-model:file-list="fileList"
            action="http://localhost:10010/user/index/uploadFile"
            list-type="picture-card"
            :headers="headers"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="onAddProd"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 编辑商品对话框 -->
  <div>
    <el-dialog v-model="dialogFormVisibleEdit" title="编辑商品" width="500">
      <el-form :model="form">
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="form.prodName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品价格" :label-width="formLabelWidth">
          <el-input v-model="form.prodPrice" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品类型" :label-width="formLabelWidth">
          <el-select
            v-model="form.prodType"
            placeholder="请选择商品类型"
            size="large"
            style="width: 240px"
            clearable
          >
            <el-option
              v-for="item in typeList"
              :key="item.dictId"
              :label="item.dictLable"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片" :label-width="formLabelWidth">
          <el-upload
            v-model:file-list="fileList"
            action="http://localhost:10010/user/index/uploadFile"
            list-type="picture-card"
            :headers="headers"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleEdit = false">取消</el-button>
          <el-button type="primary" @click="onUpdateProd"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 抽屉审核商品状态 -->
  <div>
    <el-drawer
      v-model="dialog"
      title="I have a nested form inside!"
      direction="ltr"
      class="demo-drawer"
    >
      <div class="demo-drawer__content">
        <el-form :model="checkFrom">
          <el-form-item label="商品名称" :label-width="formLabelWidth">
            {{ checkFrom.prodName }}
          </el-form-item>
          <el-form-item label="商品价格" :label-width="formLabelWidth">
            {{ checkFrom.prodPrice }}
          </el-form-item>
          <el-form-item label="商品类型" :label-width="formLabelWidth">
            {{ checkFrom.typeName }}
          </el-form-item>
          <el-form-item label="商品图片" :label-width="formLabelWidth">
            <el-image
              style="width: 50px; height: 50px"
              v-if="
                checkFrom.prodImageList != null &&
                checkFrom.prodImageList.length > 0
              "
              fit="cover"
              v-for="item in checkFrom.prodImageList"
              :key="item.imageId"
              :src="item.imageUrl"
            />
          </el-form-item>
          <el-form-item label="商品状态" :label-width="formLabelWidth">
            <el-switch
              v-model="checkFrom.prodStatus"
              inline-prompt
              active-text="审核通过"
              inactive-text="审核不通过"
              :active-value="2"
              :inactive-value="3"
            />
          </el-form-item>
          <el-form-item label="驳回理由" :label-width="formLabelWidth">
            <el-input
              type="textarea"
              v-model="checkFrom.reason"
              placeholder="请输入驳回理由"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="dialog = false">放弃</el-button>
          <el-button type="primary" @click="onClickCheck"> 提交审核 </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, ref } from "vue";
import {
  addProd,
  changeProdStatus,
  deleteProd,
  getDictList,
  getProdList,
  updateProd,
} from "../api/api";
const tableData = ref([]);
const total = ref(0);
const background = ref(false);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: null,
});
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const dialogFormVisibleEdit = ref(false);

const form = ref({
  prodName: null,
  prodPrice: null,
  prodType: null,
  prodImageList: [],
});
const typeList = ref([]);
const headers = ref({
  token: sessionStorage.getItem("token") || "",
});
const fileList = ref<UploadUserFile[]>([]);
const dialog = ref(false);
const checkFrom = ref({
  prodId: null,
  prodStatus: null,
  reason: null,
});

//商品审核方法
const onClickCheck = () => {
  changeProdStatus(checkFrom.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("提交成功");
      dialog.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

// 上线方法
const UpLine = (row: any) => {
  row.prodStatus = 1;
  changeProdStatus(row).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("提交成功");
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
// 下线方法
const DownLine = (row: any) => {};
// 审核方法(打开抽屉)
const checkProd = (row: any) => {
  Object.assign(checkFrom.value, row);
  dialog.value = true;
};

// 修改商品
const onUpdateProd = () => {
  // 图片重新添加放入提交的表单中
  let prodImageList = [];
  fileList.value.forEach((item) => {
    let img = {};
    if (item.response == undefined) {
      img.imageUrl = item.url;
    } else {
      img.imageUrl = item.response.data;
    }

    prodImageList.push(img);
  });
  form.value.prodImageList = prodImageList;
  // 提交修改
  updateProd(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("修改成功");
      dialogFormVisibleEdit.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

// 编辑方法
const handleEdit = (row: any) => {
  console.log(row);
  Object.assign(form.value, row);
  fileList.value = [];
  form.value.prodImageList.forEach((item) => {
    let img = {};
    img.url = item.imageUrl;
    fileList.value.push(img);
  });
  dialogFormVisibleEdit.value = true;
};
// 删除方法
const handleDelete = (row: any) => {
  console.log(row);
  ElMessageBox.confirm("商品删除后不可恢复,您确定要删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 确认删除
      deleteProd(row.prodId).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      // 取消删除
    });
};

// 图片方法
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

// 展示添加对话框
const ShowAddProd = () => {
  dialogFormVisible.value = true;
};
// 添加方法
const onAddProd = () => {
  fileList.value.forEach((item: any) => {
    let img = {
      imageUrl: item.response.data,
    };
    form.value.prodImageList.push(img);
  });
  addProd(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      dialogFormVisible.value = false;
      loadList();
      form.value = {
        prodName: null,
        prodPrice: null,
        prodType: null,
        prodImageList: [],
      };
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//多条件查询
const onQuetty = () => {
  loadList();
};

// 页面每条条数触发方法
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadList();
};
// 当前页面数触发方法
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadList();
};

// 分页获取商品列表
const loadList = () => {
  getProdList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

// 页面钩子函数
onMounted(() => {
  loadList();

  getDictList(1).then((res) => {
    if (res.data.code == 200) {
      typeList.value = res.data.data;
    }
  });
});
</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
